#!/usr/bin/env bash
#
# Summary: Set or show the local application-specific Node version
#
# Usage: nodenv local <version>
#        nodenv local --unset
#
# Sets the local application-specific Node version by writing the
# version name to a file named `.node-version'.
#
# When you run a Node command, nodenv will look for a `.node-version'
# file in the current directory and each parent directory. If no such
# file is found in the tree, nodenv will use the global Node version
# specified with `nodenv global'. A version specified with the
# `NODENV_VERSION' environment variable takes precedence over local
# and global versions.
#
# <version> should be a string matching a Node version known to nodenv.
# The special version string `system' will use your default system Node.
# Run `nodenv versions' for a list of available Node versions.

set -e
[ -n "$NODENV_DEBUG" ] && set -x

# Provide nodenv completions
if [ "$1" = "--complete" ]; then
  echo --unset
  echo system
  exec nodenv-versions --bare
fi

NODENV_VERSION="$1"

if [ "$NODENV_VERSION" = "--unset" ]; then
  rm -f .node-version
elif [ -n "$NODENV_VERSION" ]; then
  nodenv-version-file-write .node-version "$NODENV_VERSION"
else
  if version_file="$(nodenv-version-file "$PWD")"; then
    nodenv-version-file-read "$version_file"
  else
    echo "nodenv: no local version configured for this directory" >&2
    exit 1
  fi
fi
